package com.etonenet.service.system;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.etonenet.entity.system.security.RoleUser;
import com.etonenet.entity.system.security.RoleUserPK;
import com.etonenet.entity.system.security.UserBs;
import com.etonenet.repository.system.security.RoleUserRepository;
import com.etonenet.repository.system.security.UserBsRepository;

import esms.etonenet.boss1069.expection.ServiceLogicException;

@Service
public class UserBsService {

	@Resource
	private UserBsRepository userBsEm;

	@Resource
	private RoleUserRepository roleUserEm;

	public Page<UserBs> page(PageRequest pageRequest, Specification<UserBs> spec) {

		return userBsEm.findAll(spec, pageRequest);
	}

	@Transactional(rollbackFor = Exception.class)
	public void saveRoleUsers(Long roleId, List<Long> userIds) {

		roleUserEm.deleteByRoleId(roleId);
		for (Long userId : userIds) {

			RoleUser ru = new RoleUser();
			RoleUserPK id = new RoleUserPK();
			id.setRoleId(roleId);
			id.setUserId(userId);
			ru.setId(id);

			roleUserEm.save(ru);
		}
	}

	@Transactional(rollbackFor = Exception.class)
	public UserBs synUser(UserBs u) {

		UserBs olduser = userBsEm.findOne(u.getUserId());

		u.setLoginName(u.getLoginName().toLowerCase()); // 用户名小写

		if (olduser == null) { // 新增用户

			if (userBsEm.findByLoginName(u.getLoginName()) != null)
				throw new ServiceLogicException("user's login name duplicated"); // 用户登录名重复
		} else { // 更新用户

			if (!(olduser != null && olduser.getLoginName().equals(u.getLoginName())))
				throw new ServiceLogicException("user's login name can't be changed"); // 用户登录名不能修改
		}
		userBsEm.save(u);

		return u;
	}

}
